package replicant2;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.List;

import Common.Share;

/*
 * class to start UDP socket and listen to particular port
 */
public class UdpGameServer implements Runnable{
	
	final int MAX_LEN = 10; 
	
	private MyDatagramSocket _socket;
	private boolean _end = false;
	private GameServerImpl _gameServer;
	private Thread _thread;
    public UdpGameServer(GameServerImpl gameServer, int port) {
    	_gameServer = gameServer;
		try {
			_socket = new MyDatagramSocket(port);
		} // end try
		catch (Exception ex) {
			ex.printStackTrace();
		}
		_thread = new Thread(this);
	    _thread.start(); // Start the thread
    }

    /* function to stop this server and 
     * close the socket
     */
    public void stopServer()
    {
      _socket.close();
      _end = true;
    }
    
    /*
     * actual implementation to get current server status and return to 
     * UDP client
     */
	public void run() {	
		System.out.println(String.format("%s starts UDP server",_gameServer.getName()));
		while (!_end) {
			try {
				String message = _socket.receiveMessage();
				List<String> msglist = Arrays.asList(message.split(GameServerImpl.DELIMETER));
				if(msglist.size() > 0){
					if(msglist.get(0).equals("1")){
						String serverName = msglist.get(1);
						int receivePort = GameServerImpl.NameClientPortTable.get(serverName);
						InetAddress receiverHost = InetAddress.getByName("localhost");
						
						String replyMsg = _gameServer.getServerStatus() + Share.DELIMETER;
						_socket.sendMessage(receiverHost, receivePort, replyMsg);
					}else if(msglist.get(0).equals("2")){
						String replyMsg = "0";
						String serverName = msglist.get(1);
						int receivePort = GameServerImpl.NameClientPortTable.get(serverName);
						InetAddress receiverHost = InetAddress.getByName("localhost");
						String playerString = msglist.get(2);
						Player p = Player.DeserializeToPlayer(playerString);
						if(p!=null){
							String ret = _gameServer.createPlayerAccount(p.firstName, p.lastName, p.age, p.userName, p.password, p.iPAddress);
							if(ret.contains("1")){
								replyMsg = "1";
							}
						}
						_socket.sendMessage(receiverHost, receivePort, replyMsg);
					}else{
						
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	
}



